package com.gw.ycny.utils;

import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PearsonCorrelation {
    public double getPearsonCorrelation(List<Double> windPower , List<Double> solarPower){
        Double[] doubles=new Double[windPower.size()];
        Double[] windPower1 = windPower.toArray(doubles);

        Double[] doubles1=new Double[solarPower.size()];
        Double[] solarPower1 = solarPower.toArray(doubles1);

        // Calculate the Pearson correlation coefficient
        return calculatePearsonCoefficient(windPower1, solarPower1);
    }

    public double calculatePearsonCoefficient(Double[] xValues, Double[] yValues) {
        // Calculate the mean of x and y values
        double xMean = calculateMean(xValues);
        double yMean = calculateMean(yValues);

        // Calculate the standard deviation of x and y values
        double xStandardDeviation = calculateStandardDeviation(xValues);
        double yStandardDeviation = calculateStandardDeviation(yValues);

        // Calculate the covariance of x and y values
        double covariance = calculateCovariance(xValues, yValues);

        // Calculate the Pearson correlation coefficient
        double pearsonCoefficient = covariance / (xStandardDeviation * yStandardDeviation);

        return (double)Math.round(pearsonCoefficient*100)/100;
    }

    private double calculateMean(Double[] values) {
        double sum = 0;

        for (double value : values) {
            sum += value;
        }

        return sum / values.length;
    }

    private double calculateStandardDeviation(Double[] values) {
        double mean = calculateMean(values);
        double sum = 0;

        for (double value : values) {
            sum += Math.pow(value - mean, 2);
        }

        return Math.sqrt(sum / (values.length - 1));
    }

    private double calculateCovariance(Double[] xValues, Double[] yValues) {
        double xMean = calculateMean(xValues);
        double yMean = calculateMean(yValues);
        double sum = 0;

        for (int i = 0; i < xValues.length; i++) {
            sum += (xValues[i] - xMean) * (yValues[i] - yMean);
        }

        return sum / (xValues.length - 1);
    }
}
